package org.white.word2pdf.service;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.white.word2pdf.ErrorException;
import org.white.word2pdf.enums.ComponentType;
import org.white.word2pdf.utils.FileTypeUtil;

@Service
public class Word2PdfService {

    private final Map<ComponentType, Word2PdfStrategyInterface> strategyMap;

    public Word2PdfService(List<Word2PdfStrategyInterface> strategyInterfaces) {
        strategyMap = new HashMap<>();
        strategyInterfaces.forEach(s -> strategyMap.put(s.getType(), s));
    }

    public void convert(String type, InputStream is) {
//        try {
//            is.mark(31);
//            byte[] bytes  = new byte[30];
//            is.read(bytes, 0, 30);
//            String fileType = FileTypeUtil.getFileTypeByBytes(bytes);
//            System.out.println(fileType);
//            is.reset();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        ComponentType componentType = ComponentType.of(type);
        ByteOutputStream bos = new ByteOutputStream();
        strategyMap.get(componentType).convertToPdf(is, bos);
        String fileTempName = UUID.randomUUID() + ".pdf";
        System.out.println(fileTempName);
        try {
            // MAC下/var/folders/nm/1_z_y76n0q15d58987cbhbgh0000gn/T
            FileUtils.writeByteArrayToFile(File.createTempFile(fileTempName, ".pdf"), bos.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
            throw new ErrorException("转换后保存文件失败");
        }
    }
}
